package com.gebogebo.mobile.parking.dao;

import java.util.ArrayList;
import java.util.List;

import com.amazonaws.services.simpledb.model.Attribute;
import com.amazonaws.services.simpledb.model.Item;
import com.amazonaws.services.simpledb.model.ReplaceableAttribute;
import com.amazonaws.services.simpledb.model.ReplaceableItem;
import com.gebogebo.mobile.parking.calculator.GeoDistanceHelper;
import com.gebogebo.mobile.parking.sdb.SimpleDBClient;
import com.gebogebo.mobile.parking.model.*;

public class ParkingSpotDAO {
 
	
	public boolean addParkingSpot(List<ParkingSpot> pkSpots) {
		List<ReplaceableItem> sampleData = new ArrayList<ReplaceableItem>();
		
		for(ParkingSpot pkSpot : pkSpots) {
			sampleData.add(new ReplaceableItem().withAttributes(new ReplaceableAttribute("parking_id",pkSpot.getParkingId().toString(),true)
			, new ReplaceableAttribute("user_id",pkSpot.getUserId().toString(),true)
			,new ReplaceableAttribute("available_spots",pkSpot.getAvailableSpots().toString(),true)
			,new ReplaceableAttribute("total_spots",pkSpot.getTotalSpots().toString(),true)
			,new ReplaceableAttribute("latitude",pkSpot.getLatitude().toString(),true)
			,new ReplaceableAttribute("longitude",pkSpot.getLongitude().toString(),true)
			));
			
		}
		
	   boolean flag = SimpleDBClient.putData("parking_spot", sampleData);
		return flag;
	}
	
	
	public List<ParkingSpot> searchForParkingSpot(SearchArea area) {
		
		List<ParkingSpot> listPS = new ArrayList<ParkingSpot>();
		
		String query = GeoDistanceHelper.findPlacesWithinDistance(area);
		
		List<Item> items = SimpleDBClient.getData("parking_slots", query);
		
		for(Item item : items) {
			ParkingSpot pkSpot = new ParkingSpot();
			
			for(Object attributeObject  : item.getAttributes()) {
				Attribute attribute = (Attribute)attributeObject;
				
				String name = attribute.getName();
				String value = attribute.getValue();
				
				if("parking_id".equals(name)) {
					pkSpot.setParkingId(Long.getLong(value));
				}
				if("user_id".equals(name)) {
					pkSpot.setUserId(Long.getLong(value));
				}
				if("is_paid".equals(name)) {
					pkSpot.setPaid(Boolean.parseBoolean(value));
				}
				if("amount_per_slot".equals(name)) {
					pkSpot.setAmountPerSpot(Double.valueOf(value));
				}
				
				if("available_spots".equals(name)) {
					pkSpot.setAvailableSpots(Integer.getInteger(value));
					
				}
				if("total_spots".equals(name)) {
					pkSpot.setTotalSpots(Integer.getInteger(value));
				}
				if("latitude".equals(name)) {
					pkSpot.setLatitude(Double.valueOf(value));
				}
				if("longitude".equals(name)) {
					pkSpot.setLongitude(Double.valueOf(value));
				}
				
			}
			listPS.add(pkSpot);
		}
		return listPS;
	}
}
